/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Materials;

import Raytracing.BoundingBox;
import Raytracing.Geometry.Triangle;
import Raytracing.Shaders.Material;
import TweetRay.Box;
import TweetRay.Entity;
import TweetRay.GeometryGenerator;
import TweetRay.UTFWriter;
import java.util.ArrayList;
import processing.core.PVector;

/**
 *
 * @author Matt
 */
public class TreeGenerator extends GeometryGenerator {

    Material[] robomat = new Material[2];

    public TreeGenerator() {
        setName("Tree");

        type = MaterialFactory.Materials.TREE_GENERATOR.ordinal();

        robomat[0] = MaterialFactory.buildMatte("Trunk", new PVector(.1f, .2f, .1f));
        robomat[1] = MaterialFactory.buildMatte("Leaves", new PVector(.3f, .6f, .3f));
    }

    public void generate(Box bounds, ArrayList<Entity> entities, Material[] shaders) {

        PVector center = bounds.getCentroid();
        ArrayList<Box> temp = new ArrayList();


        float trunkRad = 2;
        float treeHeight = 75;
        float trunkHeight = 30f;
        float foliageHeight = treeHeight - trunkHeight;

        for (int t = 0; t < 20; t++) {

            double tx = center.x + Math.random()*250 - 125;
            double tz = center.z + Math.random()*250 - 125;
            
            //Trunk
            temp.add(new Box((int)(tx), (int) center.y, (int)(tz), trunkRad, trunkHeight, trunkRad, 0, 0, 0, robomat, 0));


            float rad = 5;
            float spread = 10;


            //leaves

            for (int i = 1; i < 20; i++) {

                double zHeight = Math.random() * (foliageHeight) + (foliageHeight) / 2;
                temp.add(new Box((int) tx+ (int) (Math.random() * 2 * spread - spread),
                        (int) (center.y - trunkHeight - zHeight),
                        (int) tz + (int) (Math.random() * 2 * spread - spread),
                        rad, rad, rad, 0, 0, 0, robomat, 1));

            }
        }
        //we need to find the extents of the objects that will be added so that
        //we can scale and rotate them to fit into the passed in box
        BoundingBox bb = new BoundingBox();

        for (Box b : temp) {
            for (Triangle tri : b.tris) {
                bb.contain(tri);
            }
        }

        PVector delta = bounds.getCentroid();
        delta.sub(bb.getCentroid());

        delta.mult(1.f);


        float sy = bb.getYDim();
        PVector by = bounds.getLocalXAxis(false);
        float ly = by.mag();



        for (Box b : temp) {
            b.translate(delta);

        }

        entities.addAll(temp);

    }

    public void pack(UTFWriter output) {
        throw new UnsupportedOperationException("Not supported yet.");
    }
}
